package com.cipe.cmrs.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.web.filter.OncePerRequestFilter;

import com.cipe.cmrs.util.SessionHistoryRepository;

public class HistoryTrackerFilter extends OncePerRequestFilter implements ServletContextListener, HttpSessionListener {
    private static final String IGNORE_REQUEST = "ignoreRequest";

    public void contextDestroyed(ServletContextEvent sce) {
        SessionHistoryRepository.INSTANCE.clear();
    }

    public void contextInitialized(ServletContextEvent sce) {
        // Do nothing
    }

    public void sessionCreated(HttpSessionEvent se) {
        SessionHistoryRepository.INSTANCE.initializeHistory(se.getSession());
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        SessionHistoryRepository.INSTANCE.removeHistory(se.getSession());
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
        String acceptType = request.getHeader("Accept");
        // Ignore json requests
        if ("GET".equalsIgnoreCase(request.getMethod()) && !acceptType.toUpperCase().contains("JSON")) {
            HttpSession session = request.getSession();
            SessionHistoryRepository.INSTANCE.updateSessionHistory(request);
            session.setAttribute(IGNORE_REQUEST, false);
        } else {
            request.setAttribute(IGNORE_REQUEST, true);
        }
        chain.doFilter(request, response);
    }

}
